from __future__ import with_statement

import datetime, time
import Queue as queue
import cStringIO

class SimpleLogging(object):
    __slots__ = [ '__logFileName', '__mode', '__startTime', '__endTime', '__done', '__f', '__q' ]
    
    @staticmethod
    def __fmttime(t): 
        return datetime.datetime.fromtimestamp(t).isoformat(' ')

    def __init__(self, logFileName, mode="wb"):
        self.__logFileName = logFileName
        self.__mode = mode
        assert "w" in mode or "a" in mode
        self.__done = False
        
    def __enter__(self):
        self.__startTime = time.time()
        self.__q = queue.Queue()
        if self.__logFileName:
            self.__f = open(self.__logFileName, self.__mode)
            self.__f.write("start: %s\n" % SimpleLogging.__fmttime(self.__startTime))
        else:
            self.__f = cStringIO.StringIO()
        return self.__q
    
    def __exit__(self, exc_type, exc_value, traceback):
        f = self.__f
        while not self.__q.empty():
            logText = self.__q.get()
            f.write(logText); f.write("\n")
        endTime = self.__endTime = time.time()
        f.write("stop: %s\n" % SimpleLogging.__fmttime(endTime))
        if exc_type is not None:
            f.write("exception raised: %s" % str(exc_value))
        if self.__logFileName:
            f.close()
        self.__done = True
    
    def get_log(self):
        if self.__logFileName:
            raise ValueError("log messages have been saved to a file")
        return self.__f.getvalue()
    
    def get_starttime(self):
        return self.__startTime
    starttime = property(get_starttime, None, None)
    
    def get_endtime(self):
        return self.__endTime
    endtime = property(get_endtime, None, None)

    def get_elapsedtime(self):
        if not self.__done:
            raise ValueError("not executed")
        return self.__endTime - self.__startTime
    elapsedtime = property(get_elapsedtime, None, None)
    
if __name__ == '__main__':
    simpleLogging = SimpleLogging("tmp.txt")
    with simpleLogging as logQueue:
        logQueue.put("a message to be written to the log file")
    print "elapsedtime=", simpleLogging.elapsedtime
    